<template>
    <van-cell-group inset>
        <van-field :name="name" :label="label" input-align="right" error-message-align="right" v-model="localValue"
            :placeholder="placeholder" :disabled="disabled" :required="required" readonly :rules="rules" @click="disabledClick">
            <template #button>
                <slot></slot>
            </template>
        </van-field>
    </van-cell-group>
    <van-number-keyboard v-model="localValue" :z-index="zIndex" :extra-key="extraKey" :show="numberKeyShow"
        :maxlength="maxlength" @blur="blur" />
</template>

<script setup lang="ts">
import { ref, defineProps, onMounted, watch } from 'vue'

const props = defineProps({
    name: { type: String, default: '' },
    label: { type: String, default: '' },
    placeholder: { type: String, default: '' },
    required: { type: Boolean, default: false },
    type: { type: String, default: '' },
    rules: { type: Array<any>, default: () => [] },
    extraKey: { type: String, default: '' },
    keyValue: { type: String, default: '' },
    zIndex: { type: String, default: '120' },
    formRef: { type: Object },
    maxlength: { type: String },
    disabled: { type: Boolean, default: false }
})


onMounted(() => {
    localValue.value = props.keyValue
})

const localValue = ref('')
const numberKeyShow = ref(false)

const blur = () => {
    numberKeyShow.value = false
}

const disabledClick = () => {
    if (!props.disabled) {
        numberKeyShow.value = true
    }
}

watch(() => localValue.value, () => {
    if (numberKeyShow.value) {
        let value = localValue.value
        localValue.value = value
            .replace(/^\./g, '')
            .replace(/^-\.*/g, '-') // 首位不能以-.开头
            .replace(/\.{2,}/g, '.')
            .replace(/^(0(\d)+|\.)/g, '$2') // 首位不能为类似于 01、02的金额
            .replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
            .replace(/^(-)*(\d+)\.((\d){2}).*$/, '$1$2.$3')
        emit('update:keyValue', localValue.value)
        props.formRef?.validate(props.name)
    }
})

watch(() => props.keyValue, () => {
    if (!numberKeyShow.value) {
        localValue.value = props.keyValue
    }
})

// 发射 input 事件以通知父组件 value 的变化
const emit = defineEmits(['update:keyValue'])
</script>

<style lang="less" scoped>
:deep(.van-field__button) {
    padding-left: 0;
}
</style>